<template>
  <div class="reset-container">
    <div class="navbar">
      <router-link to="/login" class="navbar-back">
        <i class="fas fa-arrow-left nav-icon"></i>
      </router-link>
      <div class="navbar-title">重置密码</div>
      <div style="width: 24px;"></div>
    </div>

    <div class="reset-header">
      <div class="reset-logo">
        <svg class="reset-icon" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
          <path d="M237.919086 918.764983s156.768549-7.835063 260.953234-8.788846c115.758811-1.059109 300.163657 8.788846 300.163657 8.788846l191.318309 21.632731s-298.896823 17.712274-491.481966 17.577692C309.979429 957.843749 35.108571 940.397714 35.108571 940.397714l202.810515-21.632731z" fill="#FFFFFF" opacity=".5"></path>
          <path d="M145.211977 78.283337c4.765989-6.606263 13.320777-15.108389 25.78432-13.788891 10.491611 1.111771 27.390537 6.038674 46.650514 12.603977 19.766126 6.73792 43.476114 15.72864 68.312503 25.755063 44.696137 18.039954 93.561417 39.637577 130.323017 57.870628A533.735131 533.735131 0 0 1 512 152.137143c35.064686 0 69.210697 3.3792 102.022583 9.777737 35.989211-17.855634 82.727497-38.654537 125.597988-56.118126 24.608183-10.026423 48.101669-19.017143 67.689326-25.760914 19.078583-6.562377 35.845851-11.498057 46.273097-12.612754 12.501577-1.337051 21.024183 7.267474 25.719955 13.838628 5.12 7.159223 9.371063 16.828709 13.039908 27.4432 7.422537 21.480594 13.80352 50.936686 19.213166 82.970332 10.8544 64.3072 18.230126 141.80352 21.714651 193.536 0.084846 1.287314 0.002926 2.548297-0.231131 3.759543C957.671131 437.39136 971.337143 490.879269 971.337143 547.108571c0 218.135406-205.651383 394.971429-459.337143 394.971429S52.662857 765.243977 52.662857 547.108571c0-56.618423 13.853257-110.454491 38.806674-159.135451a14.587611 14.587611 0 0 1-0.73728-5.696366c3.513783-51.735406 10.959726-129.237577 21.916526-193.550628 5.459383-32.036571 11.901806-61.498514 19.397486-82.98496 3.703954-10.620343 7.998903-20.29568 13.165714-27.457829z" fill="#FFFFFF"></path>
        </svg>
      </div>
      <h1 class="reset-title">重置您的密码</h1>
      <p class="reset-subtitle">请填写以下信息验证身份并重置密码</p>
    </div>

    <div class="reset-form">
      <div v-if="errorMessage" class="error-message mb-20">{{ errorMessage }}</div>
      <div v-if="successMessage" class="success-message mb-20">{{ successMessage }}</div>
      
      <!-- 步骤1：验证身份 -->
      <form v-if="step === 1" @submit.prevent="verifyIdentity">
        <div class="form-group">
          <label class="form-label" for="username">用户名/手机号/邮箱</label>
          <input type="text" id="username" v-model="username" class="form-input" placeholder="请输入账号信息" :disabled="loading">
        </div>

        <div class="form-group">
          <label class="form-label" for="verification">验证码</label>
          <div class="verification-code-container">
            <input type="text" id="verification" v-model="verificationCode" class="form-input" placeholder="请输入验证码" :disabled="loading">
            <button 
              type="button" 
              class="verification-code-button" 
              @click="sendVerificationCode" 
              :disabled="loading || cooldown > 0"
            >
              {{ cooldown > 0 ? `${cooldown}秒后重试` : '获取验证码' }}
            </button>
          </div>
        </div>

        <button type="submit" class="btn btn-primary btn-block" :disabled="loading">
          {{ loading ? '验证中...' : '下一步' }}
        </button>
      </form>

      <!-- 步骤2：设置新密码 -->
      <form v-if="step === 2" @submit.prevent="resetPassword">
        <div class="form-group">
          <label class="form-label" for="new-password">新密码</label>
          <input type="password" id="new-password" v-model="newPassword" class="form-input" placeholder="请设置新密码" :disabled="loading">
        </div>

        <div class="form-group">
          <label class="form-label" for="confirm-password">确认密码</label>
          <input type="password" id="confirm-password" v-model="confirmPassword" class="form-input" placeholder="请再次输入新密码" :disabled="loading">
        </div>

        <div class="password-strength" v-if="newPassword">
          <div class="strength-label">密码强度：</div>
          <div class="strength-meter">
            <div 
              class="strength-value" 
              :style="{ width: passwordStrength + '%' }" 
              :class="strengthClass"
            ></div>
          </div>
          <div class="strength-text" :class="strengthClass">{{ strengthText }}</div>
        </div>

        <div class="password-tips">
          <p>密码要求：</p>
          <ul>
            <li :class="{ 'valid': hasLowerCase }">至少包含一个小写字母</li>
            <li :class="{ 'valid': hasUpperCase }">至少包含一个大写字母</li>
            <li :class="{ 'valid': hasNumber }">至少包含一个数字</li>
            <li :class="{ 'valid': hasSpecialChar }">至少包含一个特殊字符</li>
            <li :class="{ 'valid': isLongEnough }">长度至少为8个字符</li>
          </ul>
        </div>

        <button type="submit" class="btn btn-primary btn-block" :disabled="loading || !isPasswordValid">
          {{ loading ? '重置中...' : '重置密码' }}
        </button>
      </form>

      <!-- 步骤3：重置成功 -->
      <div v-if="step === 3" class="reset-success">
        <div class="success-icon">
          <i class="fas fa-check-circle"></i>
        </div>
        <h2>密码重置成功</h2>
        <p>您的密码已经成功重置，请使用新密码登录</p>
        <router-link to="/login" class="btn btn-primary btn-block">
          返回登录
        </router-link>
      </div>

      <div class="login-link" v-if="step !== 3">
        <p>记起密码了? <router-link to="/login">立即登录</router-link></p>
      </div>
    </div>
  </div>
</template>

<script>
// 模拟API服务
const mockApi = {
  // 模拟发送验证码
  sendVerificationCode: (data) => {
    return new Promise((resolve) => {
      console.log('模拟发送验证码:', data);
      // 模拟网络延迟
      setTimeout(() => {
        resolve({ status: 'success' });
      }, 1000);
    });
  },
  
  // 模拟验证码验证
  verifyResetCode: (data) => {
    return new Promise((resolve, reject) => {
      console.log('模拟验证码验证:', data);
      // 模拟网络延迟
      setTimeout(() => {
        // 模拟验证码为"123456"时验证成功
        if (data.code === '123456') {
          resolve({
            data: {
              token: 'mock-reset-token-' + Date.now()
            }
          });
        } else {
          reject({ response: { data: { message: '验证码错误' } } });
        }
      }, 1000);
    });
  },
  
  // 模拟重置密码
  resetPassword: (data) => {
    return new Promise((resolve) => {
      console.log('模拟重置密码:', data);
      // 模拟网络延迟
      setTimeout(() => {
        resolve({ status: 'success' });
      }, 1500);
    });
  }
};

export default {
  name: 'ResetPassword',
  data() {
    return {
      step: 1, // 1:验证身份, 2:设置新密码, 3:重置成功
      username: '',
      verificationCode: '',
      newPassword: '',
      confirmPassword: '',
      loading: false,
      errorMessage: '',
      successMessage: '',
      cooldown: 0,
      cooldownTimer: null,
      token: '' // 验证成功后的token
    }
  },
  computed: {
    hasLowerCase() {
      return /[a-z]/.test(this.newPassword);
    },
    hasUpperCase() {
      return /[A-Z]/.test(this.newPassword);
    },
    hasNumber() {
      return /[0-9]/.test(this.newPassword);
    },
    hasSpecialChar() {
      return /[!@#$%^&*(),.?":{}|<>]/.test(this.newPassword);
    },
    isLongEnough() {
      return this.newPassword.length >= 8;
    },
    isPasswordValid() {
      return this.hasLowerCase && this.hasUpperCase && this.hasNumber && 
             this.hasSpecialChar && this.isLongEnough && 
             this.newPassword === this.confirmPassword;
    },
    passwordStrength() {
      if (!this.newPassword) return 0;
      
      let strength = 0;
      if (this.hasLowerCase) strength += 20;
      if (this.hasUpperCase) strength += 20;
      if (this.hasNumber) strength += 20;
      if (this.hasSpecialChar) strength += 20;
      if (this.isLongEnough) strength += 20;
      
      return strength;
    },
    strengthClass() {
      if (this.passwordStrength < 40) return 'weak';
      if (this.passwordStrength < 80) return 'medium';
      return 'strong';
    },
    strengthText() {
      if (this.passwordStrength < 40) return '弱';
      if (this.passwordStrength < 80) return '中';
      return '强';
    }
  },
  methods: {
    async sendVerificationCode() {
      if (!this.username) {
        this.errorMessage = '请输入用户名/手机号/邮箱';
        return;
      }

      try {
        this.loading = true;
        this.errorMessage = '';
        this.successMessage = '';

        // 调用模拟的发送验证码API
        await mockApi.sendVerificationCode({
          username: this.username,
          type: 'reset_password'
        });

        this.successMessage = '验证码已发送，请查收（模拟验证码：123456）';
        this.startCooldown();
      } catch (error) {
        console.error('发送验证码失败:', error);
        this.errorMessage = '发送验证码失败，请稍后再试';
      } finally {
        this.loading = false;
      }
    },

    startCooldown() {
      this.cooldown = 60;
      this.cooldownTimer = setInterval(() => {
        this.cooldown--;
        if (this.cooldown <= 0) {
          clearInterval(this.cooldownTimer);
        }
      }, 1000);
    },

    async verifyIdentity() {
      if (!this.username) {
        this.errorMessage = '请输入用户名/手机号/邮箱';
        return;
      }

      if (!this.verificationCode) {
        this.errorMessage = '请输入验证码';
        return;
      }

      try {
        this.loading = true;
        this.errorMessage = '';
        this.successMessage = '';

        // 调用模拟的验证身份API
        const response = await mockApi.verifyResetCode({
          username: this.username,
          code: this.verificationCode
        });

        // 保存验证token
        this.token = response.data.token;
        
        // 进入下一步
        this.step = 2;
      } catch (error) {
        console.error('验证失败:', error);
        this.errorMessage = error.response?.data?.message || '验证码错误或已过期';
      } finally {
        this.loading = false;
      }
    },

    async resetPassword() {
      if (!this.isPasswordValid) {
        if (this.newPassword !== this.confirmPassword) {
          this.errorMessage = '两次输入的密码不一致';
        } else {
          this.errorMessage = '请设置符合要求的密码';
        }
        return;
      }

      try {
        this.loading = true;
        this.errorMessage = '';
        this.successMessage = '';

        // 调用模拟的重置密码API
        await mockApi.resetPassword({
          token: this.token,
          passwordHash: this.newPassword
        });

        // 进入成功步骤
        this.step = 3;
      } catch (error) {
        console.error('重置密码失败:', error);
        this.errorMessage = '重置密码失败，请稍后再试';
      } finally {
        this.loading = false;
      }
    }
  },
  beforeUnmount() {
    if (this.cooldownTimer) {
      clearInterval(this.cooldownTimer);
    }
  }
}
</script>

<style scoped>
.reset-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8fafc;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
  padding: 0 16px;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.navbar-back {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-title {
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
}

.nav-icon {
  color: #2d3748;
}

.reset-header {
  padding: 30px 20px 10px;
  text-align: center;
}

.reset-logo {
  width: 80px;
  height: 80px;
  margin: 0 auto 15px;
  background-color: #3490dc;
  border-radius: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.reset-icon {
  width: 60px;
  height: 60px;
  color: white;
}

.reset-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 5px;
}

.reset-subtitle {
  font-size: 14px;
  color: #718096;
  margin-bottom: 20px;
}

.reset-form {
  padding: 0 20px;
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 20px;
  text-align: left;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #4a5568;
  text-align: left;
}

.form-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background-color: white;
  transition: border-color 0.2s;
  text-align: left;
}

.form-input:focus {
  border-color: #3490dc;
  outline: none;
}

.form-input:disabled {
  background-color: #f7fafc;
  cursor: not-allowed;
}

.verification-code-container {
  display: flex;
  align-items: center;
}

.verification-code-button {
  white-space: nowrap;
  padding-left: 10px;
  color: #3490dc;
  font-weight: 500;
  background: none;
  border: none;
  cursor: pointer;
}

.verification-code-button:disabled {
  color: #a0aec0;
  cursor: not-allowed;
}

.btn {
  padding: 12px 15px;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #3490dc;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #2779bd;
}

.btn-block {
  display: block;
  width: 100%;
}

.text-primary {
  color: #3490dc;
}

.mb-20 {
  margin-bottom: 20px;
}

.login-link {
  text-align: center;
  margin-top: 30px;
  margin-bottom: 30px;
  color: #718096;
  font-size: 14px;
}

.login-link a {
  color: #3490dc;
  font-weight: 500;
}

.error-message {
  background-color: #fed7d7;
  color: #c53030;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  text-align: center;
}

.success-message {
  background-color: #c6f6d5;
  color: #2f855a;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  text-align: center;
}

.password-strength {
  margin-top: 10px;
  margin-bottom: 15px;
}

.strength-label {
  font-size: 14px;
  color: #718096;
  margin-bottom: 5px;
}

.strength-meter {
  height: 6px;
  background-color: #e2e8f0;
  border-radius: 3px;
  overflow: hidden;
}

.strength-value {
  height: 100%;
  border-radius: 3px;
  transition: width 0.3s, background-color 0.3s;
}

.strength-value.weak {
  background-color: #e53e3e;
}

.strength-value.medium {
  background-color: #ecc94b;
}

.strength-value.strong {
  background-color: #38a169;
}

.strength-text {
  font-size: 12px;
  margin-top: 5px;
  text-align: right;
}

.strength-text.weak {
  color: #e53e3e;
}

.strength-text.medium {
  color: #ecc94b;
}

.strength-text.strong {
  color: #38a169;
}

.password-tips {
  background-color: #f7fafc;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 20px;
  font-size: 13px;
}

.password-tips p {
  margin-top: 0;
  margin-bottom: 5px;
  color: #4a5568;
  font-weight: 500;
}

.password-tips ul {
  margin: 0;
  padding-left: 20px;
  color: #718096;
}

.password-tips li {
  margin-bottom: 3px;
}

.password-tips li.valid {
  color: #38a169;
}

.reset-success {
  text-align: center;
  padding: 30px 0;
}

.success-icon {
  font-size: 60px;
  color: #38a169;
  margin-bottom: 20px;
}

.reset-success h2 {
  font-size: 22px;
  margin-bottom: 10px;
}

.reset-success p {
  color: #718096;
  margin-bottom: 30px;
}
</style>
